package com.itheima.service.Impl;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.MapperFactory;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @param
 * @return
 */
public class UserServiceImpl implements UserService {
    @Override
    public List<User> findAll() {
        //定义返回值
        List<User> list=null;
        //获取session执行者对象
        SqlSession session = MapperFactory.getSqlSession();
        //获取接口的代理对象
        UserMapper mapper = session.getMapper(UserMapper.class);
        //执行接口的方法
        list=mapper.findAll();
        return list;
    }

    @Override
    public void add(User user) {
        //工具类获取执行者对象
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.add(user);
        //添加完事之后记得提交事务
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public void update(User user) {
        //工具类获取执行者
        SqlSession session = MapperFactory.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.update(user);
        //提交
        TransactionUtil.commit(session);
        TransactionUtil.close(session);
    }

    @Override
    public void delete(int i) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.delete(i);
        //提交
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }
}
